﻿///////////////////////////////////////////////////////////////////////////////
// Copyright 2016 lingzimaike@gmail.com
// GPLv2
// Author: lingzimaike
///////////////////////////////////////////////////////////////////////////////

#include "papa/net/io_runnable.h"

namespace papa {
namespace net {

	IORunnable::IORunnable(void)
		: event_base_(NULL)
		, dummy_event_(NULL)
		, load_(0)
	{

	}

	IORunnable::~IORunnable(void)
	{
		Close();
	}

	bool IORunnable::Open(void)
	{
		do
		{
			event_base_ = event_base_new();
			if (!event_base_) break;

			dummy_event_ = event_new(event_base_, -1,
				EV_TIMEOUT | EV_PERSIST, &IORunnable::OnDummy, this);
			if (!dummy_event_) break;

			struct timeval tv = { 1, 0 };
			if (0 != event_add(dummy_event_, &tv))
				break;

			return true;
		} while (false);

		Close();
		return false;
	}

	void IORunnable::Stop(void)
	{
		::event_base_loopbreak(event_base_);
	}

	void IORunnable::Run(void)
	{
		::event_base_dispatch(event_base_);
	}

	void IORunnable::Close(void)
	{
		if (dummy_event_)
		{
			event_free(dummy_event_);
			dummy_event_ = NULL;
		}

		if (event_base_)
		{
			event_base_free(event_base_);
			event_base_ = NULL;
		}
	}

	void IORunnable::OnDummy(evutil_socket_t, short, void *)
	{

	}

}}  // namespace papa::net